package com.trt.beibei.manager.redis;

import com.trt.beibei.bo.OrderMessageBO;
import com.trt.beibei.service.CouponBackService;
import com.trt.beibei.service.OrderCancelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

/**
 * 事件发布来处理（与redis回调类似）： onMessage()触发发布 ， 业务订阅  ，解耦 松耦合
 *
 * 事件发布订阅的形式解耦不用每次修改onMessage()方法，不参与具体的逻辑，只需接收到的消息要再次发布和广播，需要触发的函数只需要订阅
 */


@Component
public class TopicMessageListener2 implements MessageListener {

    @Value("${spring.redis.listen-pattern}")
    private String pattern;

    private static ApplicationEventPublisher publisher;

    public static void setPublisher(ApplicationEventPublisher publisher) {
        TopicMessageListener2.publisher = publisher;
    }

    // 只发布，不参与具体业务逻辑
    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        String topic = new String(channel);
        String expiredKey = new String(body);

        OrderMessageBO messageBO = new OrderMessageBO(expiredKey);
        TopicMessageListener2.publisher.publishEvent(messageBO);
    }
}
